package com.springboot.thymeleaf.springbootthymeleaf.controller;

import com.springboot.thymeleaf.springbootthymeleaf.entity.NbParam;
import com.springboot.thymeleaf.springbootthymeleaf.service.NbParamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @Classname ${小柯}
 * @Description TODO
 * @Date 2019/9/29 19:47
 * @Created by Administrator
 */
@Api(value = "FileController类", description = "下载文档入口")
@Controller
public class FileController {

    @Autowired
    private NbParamService paramService;


    @ApiOperation(value = "下载文档方法", notes = "下载xsl文档")
    @RequestMapping(value = "export")
    public void Export(HttpServletResponse response) throws IOException {

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");
        List<NbParam> nbparamList = paramService.getNbparamList();
        System.out.println("到这里了....................." + nbparamList.size());

        //设置要导出的文件名字
        String fileName = "kkk" + new Date() + ".xls";

        // 新增数据行，并且设置单元格数据
        int rowNum = 1;

        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = {"id", "level", "名字", "order_index", "备注", "value"};

        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString hssfRichTextString = new HSSFRichTextString(headers[i]);
            cell.setCellValue(hssfRichTextString);
        }

        //在表中存放查询到的数据放入对应的列
        for (NbParam nbParam : nbparamList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(nbParam.getId());
            row1.createCell(1).setCellValue(nbParam.getLevel());
            row1.createCell(2).setCellValue(nbParam.getName());
            row1.createCell(3).setCellValue(nbParam.getOrderIndex());
            row1.createCell(4).setCellValue(nbParam.getRemark());
            row1.createCell(5).setCellValue(nbParam.getValue());
            rowNum++;
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());

    }
}
